package com.fyy.shardingjdbc.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

//@Configuration
public class ShardingConfig {

    /**
     * 定义数据源
     */
    Map<String, DataSource> createDataSourceMap(){
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:33068/order_db?useUnicode=true&characterEncoding=utf-8&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        Map<String, DataSource> result = new HashMap<>();
        result.put("orderDb",dataSource);
        return result;
    }

    /**
     * 定义主键生成策略
     */
    private static KeyGeneratorConfiguration keyGeneratorConfiguration(){
        KeyGeneratorConfiguration result = new KeyGeneratorConfiguration("SNOWFLAKE","order_id");
        return result;
    }

    /**
     * 定义表的分片策略
     */
    TableRuleConfiguration tableRuleConfiguration(){
        TableRuleConfiguration result = new TableRuleConfiguration("t_order","t_order_$->{1..2}");
        result.setTableShardingStrategyConfig(
                new InlineShardingStrategyConfiguration("order_id","t_order_$->{order_id%2+1}"));
        result.setKeyGeneratorConfig(keyGeneratorConfiguration());
        return result;
    }

    /**
     * 定义数据源
     */
    @Bean
    DataSource getShardingDataSource() throws SQLException {
        ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
        shardingRuleConfiguration.getTableRuleConfigs().add(tableRuleConfiguration());
        Properties properties = new Properties();
        properties.put("sql.show","true");
        return ShardingDataSourceFactory.createDataSource(createDataSourceMap()
                ,shardingRuleConfiguration,properties);
    }


}
